﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Delivery_Incasement : INTPage
{
    CommonMethod comHelp = new CommonMethod();
    SqlHelp help = new SqlHelp();
    IncasementModel model = new IncasementModel();
    IncasementDAO comm = new IncasementDAO();

    #region
    private string _FilesList = "No Files For this Contract!";
    public string FilesList
    {
        get { return _FilesList; }
        set { _FilesList = value; }
    }
    public string GetFilesList()
    {
        return FilesList;
    }
    #endregion
       
    protected void Page_Load(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCodeAndCoCode(this, CommonModel.errorTimeOutUrl1);
        if (!IsPostBack)
        {
            // 页面权限
            comHelp.GetRight(this, new string[] { Session["UserCode"].ToString(), Session["CoCode"].ToString(), "Incasement" },
                Grv, new string[] { "cmdSubmit", "cmdSure" }, new int[] { Grv.Columns.Count-2,Grv.Columns.Count-1 }, CommonModel.loginOut1);
            txtDate.Value = System.DateTime.Now.ToString("yyyy-MM-dd");
            bindInti(Session["UserCode"].ToString());
        }
        CommonMethod.regAlertMessageScript(UpdHead, "deliveryOnloadApply();", this);
    }

    private void bindInti(string userCode)
    {
        if (!IsPostBack)
        {
            if (Page.Request.QueryString["contractNo"] != null && Page.Request.QueryString["tradingSoNo"] != null 
                && Page.Request.QueryString["IncasementNo"] !=null)
            {
                DataTable[] dt = comm.GetIncasementInit(Page.Request.QueryString["contractNo"].ToString(),
                    Page.Request.QueryString["tradingSoNo"].ToString(),
                    Page.Request.QueryString["IncasementNo"].ToString());
                if (dt != null && dt.Length > 1)
                {
                    DataRow row = dt[0].Rows[0];

                    txtContractNo.Text = row["ContractNoMain"].ToString();
                    txtContractNoCustomer.Text = row["ContractNoCust"].ToString();
                    txtCustomer.Text = row["CustomerName"].ToString();
                    txtSaleName.Text = row["SalesName"].ToString();
                    txtSoNo.Text = row["SONo"].ToString();
                    txtDate.Value = row["AttachedFolderCreateTime"].ToString();
                    txtRemark.Text = row["IncasementDesc"].ToString();
                    radIncasementType.SelectedValue = row["IncasementType"].ToString();

                    Grv.DataSource = dt[1];
                    Grv.DataBind();
                }
                allDiv.Disabled = true;
                imgContractNo.Disabled = true;
                imgSoNo.Disabled = true;
                imgSaleName.Disabled = true;
                imgCustomer.Disabled = true;
                imgContractNoCustomer.Disabled = true;
                imgPlantSoNo.Disabled = true;
                cmdSubmit.Visible = false;
                cmdQuery.Visible = false;
                cmdSure.Visible = false;
                Grv.Columns[Grv.Columns.Count - 1].Visible = false;
                Grv.Columns[1].Visible = false;
                lblNoFiles.Visible = false;
            }
            else { DDLBind(); }
        }
    }
          
    protected void cmdQuery_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);        
        Grv.DataSource = null;
        try
        {
            #region Condition
            string str = "select distinct T.ContractNoMain from M_SO_Trading T "
                + " where T.TradingSoNo is not null and T.DeleteFlag=0 ";

            if (!string.IsNullOrEmpty(txtSaleName.Text))
            {
                str += string.Format(" and T.ContractNoMain in (select distinct ContractNoMain from M_SalesCatalog where SalesName like '%{0}%' and DeleteFlag=0)", txtSaleName.Text);
            }
            if (!string.IsNullOrEmpty(txtCustomer.Text))
            {
                str += string.Format(" and T.ContractNoMain in (select distinct ContractNoMain from M_Customer where CustomerName like '%{0}%' and DeleteFlag=0)", txtCustomer.Text);
            }
            if (!string.IsNullOrEmpty(txtPlantSoNo.Text))
            {
                str += string.Format(" and T.ContractNoMain in (select distinct ContractNoMain from M_SO_Plant where PlantSoNo like '%{0}%' and DeleteFlag=0)", txtPlantSoNo.Text);
            }
            if (!string.IsNullOrEmpty(txtContractNo.Text))
            {
                str += string.Format(" and T.ContractNoMain like '%{0}%'", txtContractNo.Text);
            }
            if (!string.IsNullOrEmpty(txtContractNoCustomer.Text))
            {
                str += string.Format(" and T.ContractNoCust like '%{0}%'", txtContractNoCustomer.Text);
            }
            if (!string.IsNullOrEmpty(txtSoNo.Text))
            {
                str += string.Format(" and T.TradingSoNo like '%{0}%'", txtSoNo.Text);
            }
            #endregion

            ddlContractNo.DataSource = help.GetDataTable(str);
            ddlContractNo.DataValueField = "ContractNoMain";
            ddlContractNo.DataTextField = "ContractNoMain";
            ddlContractNo.DataBind();

            string soNo = txtSoNo.Text.Trim();
            string pSoNo = txtPlantSoNo.Text.Trim();

            ddlContractNo_SelectedIndexChanged(sender, e);


            if (!string.IsNullOrEmpty(soNo))
            {
                #region SoNO.
                for (int i = 0; i < ddlSoNo.Items.Count; i++)
                {
                    if (ddlSoNo.Items[i].Value.Contains(soNo))
                    {
                        ddlSoNo.SelectedIndex = i;
                        txtSoNo.Text = ddlSoNo.SelectedItem.Text;
                        // 根据 SoNo 获取Plant SoNo
                        model.ContractNoMain = ddlContractNo.SelectedItem.Text;
                        model.SoNo = ddlSoNo.SelectedItem.Text;
                        ddlPlantSoNo.DataSource = comm.GetPlantSoNoByTradingSoNo(model);
                        ddlPlantSoNo.DataValueField = "PlantSoNo";
                        ddlPlantSoNo.DataTextField = "PlantSoNo";
                        ddlPlantSoNo.DataBind();
                        ListItem item = new ListItem("请选择(Select Please)", "-1");
                        ddlPlantSoNo.Items.Insert(0, item);
                        //ddlPlantSoNo.SelectedIndex = 0;
                        if (ddlPlantSoNo.SelectedIndex > 0)
                        {
                            txtPlantSoNo.Text = ddlPlantSoNo.SelectedItem.Text;
                        }
                        break;
                    }
                }
                #endregion
            }
            if (!string.IsNullOrEmpty(pSoNo))
            {
                #region PlantSoNo.
                for (int i = 0; i < ddlPlantSoNo.Items.Count; i++)
                {
                    if (ddlPlantSoNo.Items[i].Value.Contains(pSoNo))
                    {
                        ddlPlantSoNo.SelectedIndex = i;
                        txtPlantSoNo.Text = ddlPlantSoNo.SelectedItem.Text;
                        // 根据 PlantSoNo 获取SoNo
                        if (string.IsNullOrEmpty(soNo) || soNo.Trim().Length == 0)
                        {
                            model.ContractNoMain = ddlContractNo.SelectedItem.Text;
                            model.PlantSoNo = ddlPlantSoNo.SelectedItem.Text;
                            ddlSoNo.DataSource = comm.GetTradingSoNoByPlantSoNo(model);
                            ddlSoNo.DataValueField = "TradingSoNo";
                            ddlSoNo.DataTextField = "TradingSoNo";
                            ddlSoNo.DataBind();
                            ListItem item = new ListItem("请选择(Select Please)", "-1");
                            ddlSoNo.Items.Insert(0, item);
                            //ddlSoNo.SelectedIndex = 0;
                            if (ddlSoNo.SelectedIndex > 0)
                            {
                                txtSoNo.Text = ddlSoNo.SelectedItem.Text;
                            }
                        }
                        break;
                    }
                }
                #endregion
            }
        }
        catch (Exception ex) { Log.WritLog(ex.ToString(), System.DateTime.Now.ToString()); }

        CommonMethod.regAlertMessageScript(UpdHead, "deliveryOnloadApply();", this);
    }
    //上传附件
    protected void cmdSure_Click(object sender, EventArgs e)
    {
        if (!ddlContractNo.SelectedValue.Equals("-1") &&
            !string.IsNullOrEmpty(ddlSoNo.SelectedValue) && !ddlSoNo.SelectedValue.Equals("-1"))
        {
            string filepath = FileIncasement.PostedFile.FileName;
            string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);
            string lastname = filename.Substring(filename.LastIndexOf(".") + 1);

            if (filename.Length > 0)
            {
                FileUploadAndBind(filename);
            }
            else { CommonMethod.regAlertMessage(UpdHead, "FileName Can not Null!", this); }
        }
        else
        {
            CommonMethod.regAlertMessage(UpdHead, "ContractNo && SoNo Can not Null!", this);
        }
        CommonMethod.regAlertMessageScript(UpdHead, "deliveryOnloadApply();", this);
    }
    protected void FileUploadAndBind(string filename)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);

        try
        {
            string serverpath = CreateFile(ddlContractNo.SelectedItem.Text, ddlSoNo.SelectedItem.Text);
            FileDelete(serverpath + filename);
            FileIncasement.PostedFile.SaveAs(Server.MapPath(serverpath + filename));
        }
        catch { CommonMethod.regAlertMessage(UpdHead, "Upload failed!", this); }

        string date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        model.date = date;
        model.UserCode = Session["UserCode"].ToString();
        model.ContractNoMain = ddlContractNo.SelectedItem.Text;
        model.SoNo = ddlSoNo.SelectedItem.Text;
        model.AttachedFileName = filename;
        model.PlantSoNo = (!string.IsNullOrEmpty(ddlPlantSoNo.SelectedValue) && !ddlPlantSoNo.SelectedValue.Equals("-1")) ? ddlPlantSoNo.SelectedItem.Text : "";
        //fileUploadDiv.Visible = false;

        #region FilesList Bind
        DataTable dt = comm.IncasementUploadFile(model);
            Grv.DataSource = dt;
            Grv.DataBind();
        if (dt != null && dt.Rows.Count > Grv.Rows.Count)
        {
            hidFileName.Value = hidFileName.Value + filename + "/";
        }

        if (Grv.Rows.Count > 0)
        {
            txtContractNo.Enabled = false;
            imgContractNo.Disabled = true;
            txtSoNo.Enabled = false;
            imgSoNo.Disabled = true;
            imgSaleName.Disabled = true;
            imgCustomer.Disabled = true;
            cmdSubmit.Enabled = true;
            cmdQuery.Enabled = false;
        }
        #endregion
    }
    protected bool ChechFile(string fileName, string contractNo, string soNo)
    {
        bool flagFileExit = false;
        string tempServerPath = Server.MapPath("~/IncasementUploadFiles/" + contractNo + "/" + soNo + "/" + fileName);
        FileInfo fiL = new FileInfo(tempServerPath);
        flagFileExit = fiL.Exists;
        //if (flagFileExit)
        //{
        //    CommonMethod.regAlertMessageScript(UpdHead, "ShowFileExit()", this);
        //}
        return flagFileExit;
    }
    //提交装箱单/汇总
    protected void cmdSubmit_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);

        #region 更新
        cmdSubmit.Visible = false;
        model.UserCode = Session["UserCode"].ToString();
        model.date = System.DateTime.Now.ToString("yyyy-MM-dd hh:mm");
        model.AttachedFoldersName = ddlContractNo.SelectedItem.Text + "/" + ddlSoNo.SelectedItem.Text;
        model.AttachedFolderCreateTime = model.date;
        model.ContractNoCust = txtContractNoCustomer.Text;
        model.ContractNoMain = ddlContractNo.SelectedItem.Text;
        model.IncasementType = Convert.ToInt16(radIncasementType.SelectedValue);
        model.SoNo = ddlSoNo.SelectedItem.Text;
        model.CoCode = Session["CoCode"].ToString();
        model.AttachedFileNamesNow = hidFileName.Value;
        model.IncasementDesc = txtRemark.Text;
        string temp = "";
        //if (model.IncasementType == 1)
        //{
        int n = Grv.Rows.Count;
        for (int i = 0; i < Grv.Rows.Count; i++)
        {
            CheckBox ChkSelect = (CheckBox)Grv.Rows[i].FindControl("chkRow");
            if (ChkSelect.Checked)
            {
                temp += Grv.DataKeys[i]["AttachedFileName"].ToString() + "/";
            }
        }
        //}
        model.AttachedFileNamesAll = temp;
        #endregion

        if (comm.IncasementAdd(model) > 0)
        {
            if (radIncasementType.SelectedValue.Equals("1"))
            {
                model.UserCode = Session["UserCode"].ToString();
                model.SoNo = ddlSoNo.SelectedItem.Text;
                model.Remark = txtRemark.Text;

                model.date = txtDate.Value;
                model.PlantSoNo = ddlPlantSoNo.SelectedValue;
                model.ContractNoMain = ddlContractNo.SelectedValue;
                model.ContractNoCust = txtContractNoCustomer.Text;
                model.page = this;

                string plantSoNo = string.Empty;
                if (model.PlantSoNo != null && !model.PlantSoNo.Equals("-1"))
                { plantSoNo = " Plant SoNo: " + model.PlantSoNo; }

                model.EmailTittl = string.Format("装箱单汇总(ContractNo: {0}, Trading SoNo: {1} ,{2}, 装箱时间：{3})",
                    model.ContractNoMain, model.SoNo, plantSoNo, model.date);
                model.EmailContent0 = string.Format("About Contract {0} have finished Incasemented", model.EmailTittl);

                if (comm.DeleteSentEmail(model) > 0)
                {   // 返回列表
                    Response.Redirect("IncasementList.aspx");
                }
            }
        }
        else
        {
            CommonMethod.regAlertMessage(UpdHead, "failed", this);
            cmdSubmit.Visible = true;
        }
    }
    
    protected string CreateFile(string contractNo, string soNo)
    {
        string serverpath = "~/IncasementUploadFiles/" + contractNo + "/" + soNo + "/";
        string tempServerPath = Server.MapPath(serverpath);
        if (!Directory.Exists(tempServerPath))
        {
            DirectoryInfo folder = Directory.CreateDirectory(tempServerPath);
        }
        return serverpath;
    }
    public void GetFilesListShow(string contractNo,string soNo)
    {
        string serverpath = "~/IncasementUploadFiles/" + contractNo + "/" + soNo + "/";
        StringBuilder temp = new StringBuilder();
        try
        {
            DirectoryInfo Dir = new DirectoryInfo(Server.MapPath(serverpath));
            if (Dir.GetFiles().Length > 0)
            {
                //int j = 0;
                temp.Append("<table border=\"1px\" cellpadding=\"0px\" style=\"table-layout:fixed;\" cellspacing=\"0px\"><thead>");
                temp.Append("<td style=\"width: 200px; text-algin:center;\"> ContractNo.(ITT)</td>");
                temp.Append("<td style=\"width: 200px; text-algin:center;\">  So#  </td>");
                temp.Append("<td style=\"width: 300px; text-algin:center;\"> File Name</td>");
                temp.Append("<td style=\"width: 150px; text-algin:left;\"> Download</td>");
                temp.Append("<td style=\"width: 150px; text-algin:left;\"> Delete</td></thead>");
                foreach (FileInfo fileName in Dir.GetFiles())
                {
                    temp.Append("<tr><td style=\"width: 200px; text-algin:center;\">" + contractNo + "</td>");
                    temp.Append("<td style=\"width: 200px; text-algin:center;\">" + soNo + "</td>");
                    temp.Append("<td style=\"width: 300px; text-algin:center;\">" + fileName + "</td>");
                    temp.Append("<td style=\"width: 150px; text-algin:left;\"><a href='../FilesDownLoad.aspx?filePosition=IncasementUploadFiles/"
                        + contractNo + "/" + soNo + "/" + fileName + "'>下载</a></td>");
                    temp.Append("<td style=\"width: 80px; text-algin:left; Cursor:hand\" onclick=\"fileDelete('IncasementUploadFiles/"
                        + contractNo + "/" + soNo + "/" + fileName + "')\">删除</td></tr>");
                }
                temp.Append("</table>");

                FilesList = temp.ToString();
            }
            else { FilesList = "No Files For this Contract!"; }
        }
        catch
        {
            FilesList = "No Files For this Contract!";
        }
    }

    public void DDLBind()
    {
        ListItem item = new ListItem("请选择(Select Please)", "-1");
        DataTable[] dt = DtIncasement();
        if (dt != null && dt.Length > 4)
        {
            ddlContractNo.DataSource = dt[0];
            ddlContractNo.DataValueField = "ContractNoMain";
            ddlContractNo.DataTextField = "ContractNoMain";
            ddlContractNo.DataBind();

            ddlContractNoCustomer.DataSource = dt[7];
            ddlContractNoCustomer.DataValueField = "ContractNoCust";
            ddlContractNoCustomer.DataTextField = "ContractNoCust";
            ddlContractNoCustomer.DataBind();

            ddlSoNo.DataSource = dt[1];
            ddlSoNo.DataValueField = "TradingSoNo";
            ddlSoNo.DataTextField = "TradingSoNo";
            ddlSoNo.DataBind();

            ddlSaleName.DataSource = dt[2];
            ddlSaleName.DataValueField = "SalesName";
            ddlSaleName.DataTextField = "SalesName";
            ddlSaleName.DataBind();

            ddlCustomer.DataSource = dt[3];
            ddlCustomer.DataValueField = "CustomerName";
            ddlCustomer.DataTextField = "CustomerName";
            ddlCustomer.DataBind();

            ddlPlantSoNo.DataSource = dt[4];
            ddlPlantSoNo.DataValueField = "PlantSoNo";
            ddlPlantSoNo.DataTextField = "PlantSoNo";
            ddlPlantSoNo.DataBind();
        }
        ddlContractNo.Items.Insert(0, item);
        ddlContractNoCustomer.Items.Insert(0, item);
        ddlSoNo.Items.Insert(0, item);
        ddlSaleName.Items.Insert(0, item);
        ddlCustomer.Items.Insert(0, item);
        ddlPlantSoNo.Items.Insert(0, item);

        ddlContractNo.SelectedIndex = 0;
        ddlContractNoCustomer.SelectedIndex = 0;
        ddlSoNo.SelectedIndex = 0;
        ddlSaleName.SelectedIndex = 0;
        ddlCustomer.SelectedIndex = 0;
        ddlPlantSoNo.SelectedIndex = 0;
        txtContractNo.Text = "";
        txtContractNoCustomer.Text = "";
        txtSoNo.Text = "";
        txtPlantSoNo.Text = "";
        txtSaleName.Text = "";
        txtCustomer.Text = "";
    }
    public DataTable[] DtIncasement()
    {
        if (Session["ddlIncasement"] != null)
        {
            return (DataTable[])Session["ddlIncasement"];
        }
        else { return comm.GetddlForIncasement(); }
    }
    protected void ddlContractNo_SelectedIndexChanged(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);
        if (!ddlContractNo.SelectedValue.Equals("-1"))
        {
            string contractNo = ddlContractNo.SelectedValue.ToString();
            txtContractNo.Text = contractNo;
            int nTSoNo = ddlSoNo.Items.Count;
            int nCustomer = ddlCustomer.Items.Count;
            int nSalesName = ddlSaleName.Items.Count;
            int nPSoNo = ddlPlantSoNo.Items.Count;
            DataTable[] dt = DtIncasement();
            //ContractNoCustomer
            ddlContractNoCustomer.SelectedIndex = 0;
            txtContractNoCustomer.Text = "";
            int mc = ddlContractNoCustomer.Items.Count;
            for (int i = 0; i < mc; i++)
            {
                if (ddlContractNoCustomer.Items[i].Value.Equals(contractNo))
                { ddlContractNoCustomer.SelectedIndex = i; break; }
            }
            if (!ddlContractNoCustomer.SelectedValue.Equals("-1"))
            { txtContractNoCustomer.Text = ddlContractNoCustomer.SelectedItem.Text; }
            //Tsono
            ListItem itemso = new ListItem("请选择(Select Please)", "-1");
            DataRow[] rowT = dt[1].Select(string.Format("ContractNoMain='{0}'", contractNo));
            ddlSoNo.Items.Clear();
            txtSoNo.Text = "";
            foreach (DataRow row in rowT)
            {
                ddlSoNo.Items.Add(new ListItem(row["TradingSoNo"].ToString(), row["TradingSoNo"].ToString()));
            }
            ddlSoNo.Items.Insert(0, itemso);
            ddlSoNo.SelectedIndex = 0;
            //if (ddlSoNo.Items.Count>0) { txtSoNo.Text = ddlSoNo.SelectedItem.Text; }
            //Psono
            ListItem itemplantso = new ListItem("请选择(Select Please)", "-1");
            DataRow[] rowP = dt[4].Select(string.Format("ContractNoMain='{0}'", contractNo));
            ddlPlantSoNo.Items.Clear();
            txtPlantSoNo.Text = "";
            foreach (DataRow row in rowP)
            {
                ddlPlantSoNo.Items.Add(new ListItem(row["PlantSoNo"].ToString(), row["PlantSoNo"].ToString()));
            }
            ddlPlantSoNo.Items.Insert(0, itemplantso);
            ddlPlantSoNo.SelectedIndex = 0;
            //if (ddlPlantSoNo.Items.Count>0) { txtPlantSoNo.Text = ddlPlantSoNo.SelectedItem.Text; }
            //SaleName            
            DataRow[] rowSaleName = dt[5].Select(string.Format("ContractNoMain='{0}'", contractNo));
            if (rowSaleName.Length > 0)
            {
                for (int i = 0; i < nSalesName; i++)
                {
                    if (ddlSaleName.Items[i].Value.Equals(rowSaleName[0]["SalesName"].ToString()))
                    {
                        ddlSaleName.SelectedIndex = i;
                        txtSaleName.Text = ddlSaleName.SelectedItem.Text;
                        break;
                    }
                }
            }
            else { ddlSaleName.SelectedIndex = 0; txtSaleName.Text = ""; }

            //Customer            
            DataRow[] rowCustomer = dt[6].Select(string.Format("ContractNoMain='{0}'", contractNo));
            if (rowCustomer.Length > 0)
            {
                for (int i = 0; i < nCustomer; i++)
                {
                    if (ddlCustomer.Items[i].Value.Equals(rowCustomer[0]["CustomerName"].ToString()))
                    {
                        ddlCustomer.SelectedIndex = i;
                        txtCustomer.Text = ddlCustomer.SelectedItem.Text;
                        break;
                    }
                }
            }
            else { ddlCustomer.SelectedIndex = 0; txtCustomer.Text = ""; }
        }
        else
        {
            ddlContractNoCustomer.SelectedIndex = 0;
            ddlSoNo.SelectedIndex = 0;
            ddlSaleName.SelectedIndex = 0;
            ddlCustomer.SelectedIndex = 0;
            ddlPlantSoNo.SelectedIndex = 0;
        }
        BindFiles();
        CommonMethod.regAlertMessageScript(UpdHead, "deliveryOnloadApply();", this);
    }
    protected void ddlSoNo_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!ddlSoNo.SelectedValue.Equals("-1"))
        { txtSoNo.Text = ddlSoNo.SelectedItem.Text; }
        else { txtSoNo.Text = ""; }
        BindFiles();
        CommonMethod.regAlertMessageScript(UpdHead, "showHidden('imgContractNo','ddlSoNo', 'txtSoNo','imgContractNo')", this);
    }
    protected void ddlSaleName_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTable[] dt = DtIncasement();
        if (ddlSaleName.SelectedValue.Equals("-1")) { DDLBind(); }
        else
        {
            txtSaleName.Text = ddlSaleName.SelectedItem.Text;
            DataRow[] row = dt[5].Select(string.Format("SalesName='{0}'", txtSaleName.Text));
            ddlContractNo.Items.Clear();
            txtContractNo.Text = "";
            foreach (DataRow r in row)
            {
                ddlContractNo.Items.Add(new ListItem(r["ContractNoMain"].ToString(), r["ContractNoMain"].ToString()));
            }
            if (ddlContractNo.Items.Count > 0)
            {
                txtContractNo.Text = ddlContractNo.SelectedItem.Text;
                DataRow[] rowCustomer = dt[6].Select(string.Format("ContractNoMain='{0}'", txtContractNo.Text));
                if (rowCustomer.Length > 0)
                {
                    ddlCustomer.SelectedValue = rowCustomer[0]["CustomerName"].ToString();
                    txtCustomer.Text = ddlCustomer.SelectedItem.Text;
                }
                else { ddlCustomer.SelectedIndex = 0; }
                try { ddlContractNoCustomer.SelectedValue = txtContractNo.Text; txtContractNoCustomer.Text = ddlContractNoCustomer.SelectedItem.Text; }
                catch { }

                //Tsono
                ListItem itemso = new ListItem("请选择(Select Please)", "-1");
                DataRow[] rowT = dt[1].Select(string.Format("ContractNoMain='{0}'", txtContractNo.Text));
                ddlSoNo.Items.Clear();
                txtSoNo.Text = "";
                foreach (DataRow r in rowT)
                {
                    ddlSoNo.Items.Add(new ListItem(r["TradingSoNo"].ToString(), r["TradingSoNo"].ToString()));
                }
                ddlSoNo.Items.Insert(0, itemso);
                ddlSoNo.SelectedIndex = 0;
                //if (ddlSoNo.Items.Count > 0) { txtSoNo.Text = ddlSoNo.SelectedItem.Text; }
                //Psono
                ListItem itemplantso = new ListItem("请选择(Select Please)", "-1");
                DataRow[] rowP = dt[4].Select(string.Format("ContractNoMain='{0}'", txtContractNo.Text));
                ddlPlantSoNo.Items.Clear();
                txtPlantSoNo.Text = "";
                foreach (DataRow r in rowP)
                {
                    ddlPlantSoNo.Items.Add(new ListItem(r["PlantSoNo"].ToString(), r["PlantSoNo"].ToString()));
                }
                ddlPlantSoNo.Items.Insert(0, itemplantso);
                ddlPlantSoNo.SelectedIndex = 0;
                //if (ddlPlantSoNo.Items.Count > 0) { txtPlantSoNo.Text = ddlPlantSoNo.SelectedItem.Text; }
            }
            else
            {
                ddlContractNoCustomer.SelectedIndex = 0;
                txtContractNoCustomer.Text = "";
                ddlSoNo.SelectedIndex = 0;
                txtSoNo.Text = "";
                ddlPlantSoNo.SelectedIndex = 0;
                txtPlantSoNo.Text = "";
                ddlCustomer.SelectedIndex = 0;
            }
        }
        BindFiles();
        CommonMethod.regAlertMessageScript(UpdHead, "showHidden('imgSaleName','ddlSaleName', 'txtSaleName','imgSaleName')", this);
    }
    protected void ddlCustomer_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTable[] dt = DtIncasement();
        if (ddlCustomer.SelectedValue.Equals("-1")) { DDLBind(); }
        else
        {
            txtCustomer.Text = ddlCustomer.SelectedItem.Text;
            DataRow[] row = dt[6].Select(string.Format("CustomerName='{0}'", txtCustomer.Text));
            ddlContractNo.Items.Clear();
            txtContractNo.Text = "";
            foreach (DataRow r in row)
            {
                ddlContractNo.Items.Add(new ListItem(r["ContractNoMain"].ToString(), r["ContractNoMain"].ToString()));
            }
            if (ddlContractNo.Items.Count > 0)
            {
                txtContractNo.Text = ddlContractNo.SelectedItem.Text;
                DataRow[] rowSaleName = dt[5].Select(string.Format("ContractNoMain='{0}'", txtContractNo.Text));
                if (rowSaleName.Length > 0)
                {
                    ddlSaleName.SelectedValue = rowSaleName[0]["SalesName"].ToString();
                    txtSaleName.Text = ddlSaleName.SelectedItem.Text;
                }
                else { ddlSaleName.SelectedIndex = 0; }
                try { ddlContractNoCustomer.SelectedValue = txtContractNo.Text; txtContractNoCustomer.Text = ddlContractNoCustomer.SelectedItem.Text; }
                catch { }

                //Tsono
                ListItem itemso = new ListItem("请选择(Select Please)", "-1");
                DataRow[] rowT = dt[1].Select(string.Format("ContractNoMain='{0}'", txtContractNo.Text));
                ddlSoNo.Items.Clear();
                txtSoNo.Text = "";
                foreach (DataRow r in rowT)
                {
                    ddlSoNo.Items.Add(new ListItem(r["TradingSoNo"].ToString(), r["TradingSoNo"].ToString()));
                }
                ddlSoNo.Items.Insert(0, itemso);
                ddlSoNo.SelectedIndex = 0;
                //if (ddlSoNo.Items.Count > 0) { txtSoNo.Text = ddlSoNo.SelectedItem.Text; }
                //Psono
                ListItem itemplantso = new ListItem("请选择(Select Please)", "-1");
                DataRow[] rowP = dt[4].Select(string.Format("ContractNoMain='{0}'", txtContractNo.Text));
                ddlPlantSoNo.Items.Clear();
                txtPlantSoNo.Text = "";
                foreach (DataRow r in rowP)
                {
                    ddlPlantSoNo.Items.Add(new ListItem(r["PlantSoNo"].ToString(), r["PlantSoNo"].ToString()));
                }
                ddlPlantSoNo.Items.Insert(0, itemplantso);
                ddlPlantSoNo.SelectedIndex = 0;
                //if (ddlPlantSoNo.Items.Count > 0) { txtPlantSoNo.Text = ddlPlantSoNo.SelectedItem.Text; }
            }
            else
            {
                ddlContractNoCustomer.SelectedIndex = 0;
                txtContractNoCustomer.Text = "";
                ddlSoNo.SelectedIndex = 0;
                txtSoNo.Text = "";
                ddlPlantSoNo.SelectedIndex = 0;
                txtPlantSoNo.Text = "";
                ddlSaleName.SelectedIndex = 0;
            }
        }
        BindFiles();
        CommonMethod.regAlertMessageScript(UpdHead, "showHidden('ddlCustomer','ddlCustomer', 'txtCustomer','txtCustomer')", this);
    }   
    protected void ddlPlantSoNo_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!ddlPlantSoNo.SelectedValue.Equals("-1"))
        { txtPlantSoNo.Text = ddlPlantSoNo.SelectedItem.Text; }
        else { txtPlantSoNo.Text = ""; }
        BindFiles();
        CommonMethod.regAlertMessageScript(UpdHead, "showHidden('ddlPlantSoNo','ddlPlantSoNo', 'txtPlantSoNo','txtPlantSoNo')", this);
    }
    protected void ddlContractNoCustomer_TextChanged(object sender, EventArgs e)
    {
        if (!ddlContractNoCustomer.SelectedValue.Equals("-1"))
        { txtContractNoCustomer.Text = ddlContractNoCustomer.SelectedItem.Text; }
        else { txtContractNoCustomer.Text = ""; }
        CommonMethod.regAlertMessageScript(UpdHead, "showHidden('ddlContractNoCustomer','ddlContractNoCustomer', 'txtContractNoCustomer','txtContractNoCustomer')", this);
    }

    protected void Grv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //鼠标经过事件
        if (e.Row.RowIndex != -1)
        {
            //设置悬浮鼠标指针形状为"小手"
            e.Row.Attributes["style"] = "Cursor:hand";
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "lastColor=this.style.backgroundColor;this.style.backgroundColor='#CCCC99';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=lastColor;");
                ((LinkButton)e.Row.Cells[Grv.Columns.Count - 1].Controls[0]).Attributes.Add("onclick", "return confirm('确实要删除？');");
            }
        }
    }
    protected void Grv_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string incasementFilesID = Grv.DataKeys[e.RowIndex]["IncasementFilesID"].ToString();
        
        string StrDelete = string.Format("delete from M_IncasementFiles where IncasementFilesID='{0}'", incasementFilesID);
        if (help.RunSqlInt(StrDelete) > 0)
        {
            string attachedFileName = Grv.DataKeys[e.RowIndex]["filePath"].ToString();
            FileDelete("~/IncasementUploadFiles/" + attachedFileName);

            CommonMethod.regAlertMessage("success！", this);
            model.ContractNoMain = txtContractNo.Text;
            model.SoNo = txtSoNo.Text;
            DataTable dt = comm.GetIncasementFiles(model);
            Grv.DataSource = dt;
            Grv.DataBind();
        }
        else
        { CommonMethod.regAlertMessage(" failed！", this); }
    }
    protected void FileDelete(string strPath)
    {
        string path = Server.MapPath(strPath);
        System.IO.FileInfo fiL = new System.IO.FileInfo(path);
        if (fiL.Exists)
        {
            fiL.Delete();
        }
    }

    public void BindFiles()
    {
        model.ContractNoMain = ddlContractNo.SelectedItem.Text;
        model.SoNo = "";
        model.PlantSoNo = "";
        if (ddlSoNo.Items.Count > 0 && !ddlSoNo.SelectedValue.Equals("-1")
            && ddlPlantSoNo.Items.Count > 0 && !ddlPlantSoNo.SelectedValue.Equals("-1"))
        {
            model.SoNo = ddlSoNo.SelectedItem.Text;
            model.PlantSoNo = ddlPlantSoNo.SelectedItem.Text;
        }
        else if (ddlSoNo.Items.Count > 0 && !ddlSoNo.SelectedValue.Equals("-1"))
        {
            model.SoNo = ddlSoNo.SelectedItem.Text;
        }
        else if (ddlPlantSoNo.Items.Count > 0 && !ddlPlantSoNo.SelectedValue.Equals("-1"))
        {
            model.PlantSoNo = ddlPlantSoNo.SelectedItem.Text;
        }
        Grv.DataSource = comm.GetIncasementFiles(model);
        Grv.DataBind();
        lblNoFiles.Visible = false;
    }
    protected void radIncasementType_TextChanged(object sender, EventArgs e)
    {
        if (radIncasementType.SelectedValue.Equals("1"))
        { cmdSubmit.Enabled = true; }
    }

    protected void cmdSure2_Click(object sender, EventArgs e)
    {
        allDiv.Visible = true;
        //fileUploadDiv.Visible = false;
        if (!ddlContractNo.SelectedValue.ToString().Equals("-1") && !string.IsNullOrEmpty(ddlSoNo.SelectedValue.ToString())
            && !ddlSoNo.SelectedValue.ToString().Equals("-1"))
        {
            string filename = hidfilenameExit.Value.ToString();

            if (filename.Length > 0)
            { FileUploadAndBind(filename); }
            else { CommonMethod.regAlertMessage(UpdHead, "FileName Can not Null!", this); }
        }
        else
        {
            CommonMethod.regAlertMessage(UpdHead, "ContractNo && SoNo Can not Null!", this);
        }
        CommonMethod.regAlertMessageScript(UpdHead, "deliveryOnloadApply();", this);
    }
    protected void cmdCancel_Click(object sender, EventArgs e)
    {
        //fileUploadDiv.Visible = false;
        allDiv.Visible = true;
    }
}